package com.comsoftstar.nt5s.Activity;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.hzc.nt5s.IConstant;
import com.hzc.nt5s.R;
import com.hzc.nt5s.adapter.SearchDateAdapter;
import com.hzc.nt5s.utils.JsonComparator;
import com.hzc.nt5s.utils.Tools;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SearchActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView tv_back;
    private Button btn_search;
    private Context mContext;
    private TextView tv_start_date;
    private TextView tv_end_date;
    private TextView tv_workgroup;
    private Calendar calendar;
    private ProgressDialog progressDialog;
    private ListView listView;
    private int current_start_end_date_state = 1;
    private StringBuffer group=new StringBuffer(1000);
    private ArrayList<String> list_group;
    private String strs_group[];
    private SearchDateAdapter adapter;
    private JSONArray ja, ja_notpass;
    public JSONArray organization;
    public Map<String, String> map;
    private CheckBox checkBox;
    private JSONObject jsonObject;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        mContext = SearchActivity.this;
        initView();
        setup();
    }
    private void initView() {
        ja_notpass = new JSONArray();
        progressDialog = new ProgressDialog(mContext);
        progressDialog.setMessage("正在获取数据，请稍候");
        calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        tv_end_date = (TextView) findViewById(R.id.tv_end_date);
        tv_start_date = (TextView) findViewById(R.id.tv_start_date);
        tv_workgroup = (TextView) findViewById(R.id.tv_workgroup);
        btn_search = (Button) findViewById(R.id.btn_search);
        tv_back = (TextView) findViewById(R.id.tv_back);
        listView = (ListView) findViewById(R.id.lv_results);
        list_group = new ArrayList<>();
        map = new HashMap<>();
        checkBox = (CheckBox) findViewById(R.id.shownotpass);
    }

    private void setup() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String date = format.format(calendar.getTime());
        //初始得到用户的数据
        getOrganization();
        tv_end_date.setText(date);
        calendar.add(Calendar.MONTH, -2);
        date = format.format(calendar.getTime());
        tv_start_date.setText(date);            //两个月前的数据
        tv_end_date.setOnClickListener(this);
        tv_start_date.setOnClickListener(this);
        tv_back.setOnClickListener(this);
        tv_workgroup.setOnClickListener(this);
        btn_search.setOnClickListener(this);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long length) {


                Intent intent = new Intent();
                intent.setClass(SearchActivity.this, DetailActivity.class);
                try {
                    if (!checkBox.isChecked()) {
                        jsonObject = (JSONObject) ja.get(position);
                    } else {
                        jsonObject = (JSONObject) ja_notpass.get(position);
                    }
                    jsonObject.put("groupName", getKey(jsonObject.optString("WorkShop")));
                    for (int i = 0; i < organization.length(); i++) {
                        JSONObject object = (JSONObject) organization.get(i);
                        if (object.optString("DeptNo").equals(jsonObject.optString("WorkShop"))) {
                            jsonObject.put("Director", object.optString("Director"));
                            jsonObject.put("PosLeader", object.optString("PosLeader"));
                            jsonObject.put("DeputyLeader", object.optString("DeputyLeader"));
                        }
                    }
                    intent.putExtra("detail", jsonObject.toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                startActivityForResult(intent,1);
            }
        });
        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean ischecked) {
                if (ja != null && ja.length() > 0) {
                    if (ischecked) {
                        try {
                            if (ja != null && ja.length() > 0) {
                                ja_notpass = ja;
                                List list = new ArrayList();
                                for (int i = 0; i < ja_notpass.length(); i++) {
                                    JSONObject jsonObject = (JSONObject) ja_notpass.get(i);
                                    if (jsonObject.optString("ISOK").equals("0")) {
                                        list.add(ja_notpass.get(i));
                                    }
                                }
                                ja_notpass = new JSONArray(list);

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        adapter.refresh(ja_notpass, map);
                    } else {
                        adapter.refresh(ja, map);
                    }
                }
            }
        });

    }
//初始得到用户的数据
    private void getOrganization() {
        RequestParams params = new RequestParams(IConstant.URL + "getOrganization");
//        System.out.println("请求的URL：" + params.toString());
        x.http().post(params, new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(String result) {
//                System.out.println("返回结果：" + result);
                try {
                    organization = new JSONArray(result);
                    for (int i = 0; i < organization.length(); i++) {
                        JSONObject jo  = (JSONObject) organization.get(i);
                        list_group.add(jo.optString("DeptName")); //获取车间名字列表
                        map.put(jo.optString("DeptName"), jo.optString("DeptNo"));
                    }
                    strs_group = (String[]) list_group.toArray(new String[0]);
//                    System.out.println("部门名称" + strs_group);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    @Override
    public void onClick(View view) {
        Calendar calendar = Calendar.getInstance();
        switch (view.getId()) {
            case R.id.tv_back:
                finish();
                break;
            case R.id.btn_search:
                if (Tools.isNetAvailuable(mContext)) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    try {
                        Date d1 = sdf.parse(tv_start_date.getText().toString());
                        Date d2 = sdf.parse(tv_end_date.getText().toString());
                        if (d1.after(d2)) {
                            Tools.showToast(mContext, "开始日期要在结束日期之后");
                        } else if (daysBetween(d1, d2) > 90) {
                            Tools.showToast(mContext, "日期间隔不能超过3个月");
                        } else {
                            progressDialog.show();
                            //加载数据
                            getDataFromNet();
                        }
                    } catch (ParseException ignored) {

                    }

                } else {
                    Tools.showToast(mContext, "当前网络不可用，请检查网络");
                }

                break;
            case R.id.tv_start_date:
                current_start_end_date_state = 1;
                DatePickerDialog dpd = new DatePickerDialog(mContext, Datelistener, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
                dpd.show();

                break;
            case R.id.tv_end_date:
                current_start_end_date_state = 2;
                DatePickerDialog dpd2 = new DatePickerDialog(mContext, Datelistener, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
                dpd2.show();
                break;
            case R.id.tv_workgroup:
                showGroupDialog();
                break;

        }
    }

    private void showGroupDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("车间组别");
        group.delete(0,group.length());

        builder.setMultiChoiceItems(strs_group,null, new DialogInterface.OnMultiChoiceClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which, boolean isChecked) {

                if (isChecked){
                    group.append(strs_group[which]+",");
                }

            }

        });

        builder.setPositiveButton("确定", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                tv_workgroup.setText(group.deleteCharAt(group.length()-1).toString());
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {

            }
        });
        builder.show();
    }



    private DatePickerDialog.OnDateSetListener Datelistener = new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int myyear, int monthOfYear, int dayOfMonth) {
            String month="";
            String day="";
            if (monthOfYear<9){
                month="0"+(monthOfYear+1);
            }else {
                month=""+(monthOfYear+1);
            }
            if (dayOfMonth<10){
                day="0"+dayOfMonth;
            }else {
                day=""+dayOfMonth;
            }
            if (current_start_end_date_state == 2) {
                tv_end_date.setText(myyear + "-" +month + "-" + day);
            } else {
                tv_start_date.setText(myyear + "-" +month + "-" + day);
            }

        }
    };

    public static int daysBetween(Date smdate, Date bdate) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        smdate = sdf.parse(sdf.format(smdate));
        bdate = sdf.parse(sdf.format(bdate));
        Calendar cal = Calendar.getInstance();
        cal.setTime(smdate);
        long time1 = cal.getTimeInMillis();
        cal.setTime(bdate);
        long time2 = cal.getTimeInMillis();
        long between_days = (time2 - time1) / (1000 * 3600 * 24);
        return Integer.parseInt(String.valueOf(between_days));
    }

    //调用接口
    private void getDataFromNet() {
        RequestParams params = new RequestParams(IConstant.URL + "getReviewList");
        params.addBodyParameter("beginDate", tv_start_date.getText().toString());
        params.addBodyParameter("endDate", tv_end_date.getText().toString());
        map.put("请选择车间", "");
//        params.addBodyParameter("groupName",tv_workgroup.getText().toString());

        StringBuffer stringBuffer=new StringBuffer(1000);

        for (int i=0;i<tv_workgroup.getText().toString().split(",").length;i++){
            stringBuffer.append(map.get(tv_workgroup.getText().toString().split(",")[i])+",");
        }
        stringBuffer.deleteCharAt(stringBuffer.length()-1);

        params.addBodyParameter("groupName", stringBuffer.toString());
        System.out.println("请求的URL：" + params.toString());
        x.http().post(params, new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(String result) {
                progressDialog.dismiss();
//                System.out.println("返回结果：" + result);
                try {

                    ja = new JSONArray(result);

                    if (ja != null && ja.length() > 0) {
//                        System.out.println("JSONArray:"+ja);
                        if (checkBox.isChecked()) {
                            if (ja != null && ja.length() > 0) {   //可删除
                                ja_notpass = ja;
                                List list = new ArrayList();
                                for (int i = 0; i < ja_notpass.length(); i++) {
                                    JSONObject jsonObject = (JSONObject) ja_notpass.get(i);
                                    if (jsonObject.optString("ISOK").equals("0")) {
                                        list.add(ja_notpass.get(i));
                                    }
                                }
                                ja_notpass = new JSONArray(list);
                            }
                            //有点重复操作的意思  复制到另一个list集合里面
                            List<JSONObject> list = new ArrayList<JSONObject> ();
                            JSONObject jsonObj = null;
                            for (int i = 0; i < ja_notpass.length(); i++) {
                                jsonObj = ja_notpass.optJSONObject(i);
                                list.add(jsonObj);
                            }
                            //排序操作
                            JsonComparator pComparator =  new JsonComparator("CheckDate");
                            Collections.sort(list, pComparator);
                            //把数据放回去
                            ja_notpass = new JSONArray();
                            for (int i = 0; i < list.size(); i++) {
                                jsonObj = list.get(i);
                                ja_notpass.put(jsonObj);
                            }
                            adapter = new SearchDateAdapter(mContext, ja_notpass, map);
                            listView.setAdapter(adapter);
                        } else {
                            List<JSONObject> list = new ArrayList<JSONObject> ();
                            JSONObject jsonObj = null;
                            for (int i = 0; i < ja.length(); i++) {
                                jsonObj = ja.optJSONObject(i);
                                list.add(jsonObj);
                            }
                            //排序操作
                            JsonComparator pComparator =  new JsonComparator("CheckDate");
                            Collections.sort(list, pComparator);

                            //把数据放回去
                            ja = new JSONArray();
                            for (int i = 0; i < list.size(); i++) {
                                jsonObj = list.get(i);
                                ja.put(jsonObj);
                            }
                            adapter = new SearchDateAdapter(mContext, ja, map);
                            listView.setAdapter(adapter);
                        }
                    }

                } catch (JSONException e) {
                    System.out.println("解析错误：" + e.toString());
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                progressDialog.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                progressDialog.dismiss();
                Toast.makeText(mContext, "cancelled", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFinished() {
                progressDialog.dismiss();
            }
        });

    }

    public String getKey(String value) {
        String key = new String();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            if (value.equals(entry.getValue())) {
                key = entry.getKey();
            } else {
                continue;
            }
        }
        return key;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case 1:
                getDataFromNet();
        }
    }

}
